package com.scrcu.core.batch.biz;

import com.scrcu.core.batch.dao.SqlSessionDao;
import com.scrcu.core.batch.entity.BatchLock;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class BatchLockBizImpl extends SqlSessionDao implements BatchLockBiz {

    private final String namespace = "com.scrcu.core.batch.BatchLock.";

    public BatchLockBizImpl(SqlSession dao) {
        super(dao);
    }

    @Override
    @Transactional(readOnly = true)
    public BatchLock get(String code) {
        return dao.selectOne(namespace.concat("selectByCode"), code);
    }

    @Override
    @Transactional
    public Object save(BatchLock o) {
        BatchLock batchLock = dao.selectOne(namespace.concat("selectByCode"), o.getCode());
        if (batchLock == null) {
            return dao.insert(namespace.concat("insert"), o);
        } else {
            return dao.update(namespace.concat("update"), o);
        }
    }

    @Override
    @Transactional
    public boolean optimisticLock(BatchLock batchLock, String addr) {
        batchLock.setAddr(addr);
        int i = dao.update(namespace.concat("optimisticLock"), batchLock);
        if (i == 1)
            return true;
        return false;
    }

    @Override
    @Transactional
    public boolean pessimisticLock(String code, String addr) {
        BatchLock batchLock = dao.selectOne(namespace.concat("selectForUpdate"), code);
        batchLock.setAddr(addr);
        int i = dao.update(namespace.concat("pessimisticLock"), batchLock);
        if (i == 1)
            return true;
        return false;
    }

    @Override
    @Transactional
    public boolean updateStatus(String code, short status) {
        BatchLock batchLock = dao.selectOne(namespace.concat("selectForUpdate"), code);
        batchLock.setStatus(status);
        int i = dao.update(namespace.concat("updateStatus"), batchLock);
        if (i == 1)
            return true;
        return false;
    }
}
